import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';

abstract class ViewListController<T> extends GetxController {
  final _logger = Get.find<Logger>();

  // 核心状态变量
  final list = <T>[].obs;
  final _page = 1.obs;
  final _isLoading = false.obs;
  final _errorMsg = ''.obs;

  final hasMore = true.obs; // 是否还有更多数据
  final state = ViewState.busy.obs;

  final int perPage; // 每页数量

  ViewListController({this.perPage = 20});

  // Getter方法（外部只读访问）
  String get errorMsg => _errorMsg.value;

  @override
  void onReady() {
    load(isRefresh: true);
    super.onReady();
  }

  Future<void> load({bool isRefresh = false}) async {
    // 避免重复加载或没有更多数据时加载
    if (_isLoading.value || (!isRefresh && !hasMore.value)) return;

    try {
      _isLoading.value = true;
      state.value = ViewState.busy;

      if (isRefresh) {
        _page.value = 1;
        hasMore.value = true;
      }

      // 调用子类实现的真实数据加载
      final data = await loadData(_page.value, perPage);

      // 处理加载结果
      if (isRefresh) list.clear();

      if (data != null && data.isNotEmpty) {
        list.addAll(data);
        hasMore.value = data.length >= perPage; // 判断是否还有更多数据
        _page.value++; // 成功加载后页码+1
        state.value = ViewState.idle;
      } else {
        hasMore.value = false;
        state.value = ViewState.empty;
      }
    } catch (e) {
      state.value = ViewState.error;
      _errorMsg.value = e.toString();
      _logger.e('列表加载错误: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  /// 子类必须实现的数据加载方法
  /// @param page 当前页码
  @protected
  Future<List<T>?> loadData(int page, int perPage);
}

enum ViewState {
  busy, // 忙碌
  idle, // 空闲
  empty, // 空数据
  error, // 加载失败
}
